import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {ProductService} from "../service/product.service";
import {BarnProduct} from "../entity/barn-product";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd/message";
import {ProjectProductService} from "../../service/project-product.service";
import {BarnProject} from "../../project/entity/barn-project";

@Component({
  selector: 'app-product-usage',
  templateUrl: './product-usage.component.html',
  styleUrls: ['./product-usage.component.less']
})
export class ProductUsageComponent implements OnInit {

  product: BarnProduct
  remarkMaxLength = BarnProduct.remarkMaxLength
  remarkForm = new FormGroup({
    remark: new FormControl("", Validators.maxLength(this.remarkMaxLength))
  })

  loading = false
  loadingProject = false;

  projects: BarnProject[] = []

  constructor(private routeInfo: ActivatedRoute, private productService: ProductService, private msg: NzMessageService,
              private ppService: ProjectProductService) {
  }

  ngOnInit(): void {
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    if (pid) {
      this.loading = true
      this.productService.getById(pid).subscribe(value => {
        this.loading = false;
        this.product = value
        this.remarkForm.patchValue(value)

      });
      this.getProjects(pid)
    }
  }

  saveRemark() {
    if (this.remarkForm.valid) {
      this.product.remark = this.remarkForm.get('remark').value
      this.productService.save(this.product).subscribe(value => {
        this.msg.success("保存成功");
        this.loading = false
      }, () => this.loading = false);
    } else {
      this.remarkForm.controls[0].markAsDirty()
      this.remarkForm.controls[0].updateValueAndValidity()
    }
  }

  getProjects(pid) {
    this.loadingProject = true
    this.ppService.getProjectByProduct(pid).subscribe(value => {
      this.projects = value || [];
      this.loadingProject = false
    }, () => this.loadingProject = false);

  }

}
